package com.lh.service.impl;

import com.lh.service.PassportService;
import com.lh.mapper.UsersMapper;
import com.lh.pojo.Users;
import com.lh.pojo.bo.UserBO;
import com.lh.utils.DateUtil;
import com.lh.utils.MD5Utils;
import com.lh.enums.Sex;
import org.n3r.idworker.Sid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * @program: foodie-dev
 * @description:
 * @author: LH
 * @create: 2022-04-01 16:22
 **/
@Service
public class PassportServiceImpl implements PassportService{

    private static final Logger LOG = LoggerFactory.getLogger(PassportServiceImpl.class);

    private static final String FACE_IMG = "https://cdn.pixabay.com/photo/2022/03/28/18/41/spring-7098130_960_720.jpg";

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private Sid sid;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public boolean usernameIsExist(String username){
        Example example = new Example(Users.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("username", username);

        Users users = usersMapper.selectOneByExample(example);

        if (users == null){
            return true;
        }

        return false;
    }

    @Transactional( propagation = Propagation.REQUIRED)
    @Override
    public Users createUser(UserBO userBO) {

        String id = sid.nextShort();

        Users user = new Users();

        user.setId(id);
        user.setUsername(userBO.getUsername());
        user.setNickname(userBO.getUsername());
        user.setFace(FACE_IMG);
        try {
            user.setPassword(MD5Utils.getMD5Str(userBO.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setBirthday(DateUtil.stringToDate("1990-01-01"));
        user.setSex(Sex.SECRET.getType());
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());

        int insert = usersMapper.insert(user);

        Users users = usersMapper.selectByPrimaryKey(insert);

        return users;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Users getUserByNameAndPassword(String username, String password) {
        Example example = new Example(Users.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("username", username);
        criteria.andEqualTo("password", password);

        LOG.info("INFO:SAVE");
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        return usersMapper.selectOneByExample(example);
    }

}